package com.guigusuqi.commonutils.handler;

import com.guigusuqi.commonutils.exeception.BusinessException;
import com.guigusuqi.commonutils.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@RestControllerAdvice//对加了controller注解的方法进行拦截处理 AOP的实现
@Slf4j
public class GlobalExceptionHandler
{
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * hibernate validator 数据绑定验证异常拦截
     * @param e 绑定验证异常
     * @return 错误返回消息
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result<Boolean> validateErrorHandler(BindException e) {
        todoErrorLogger(e,e.getMessage());
        return Result.fail(e.getMessage());
    }

    /**
     * hibernate validator 数据绑定验证异常拦截
     * @param e 绑定验证异常
     * @return 错误返回消息
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Boolean> validateErrorHandler(MethodArgumentNotValidException e) {
        StringBuilder errorMessage = new StringBuilder();

        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();

        int index = 1;
        for (ObjectError error : allErrors) {
            //  获取参数名
            DefaultMessageSourceResolvable argument = (DefaultMessageSourceResolvable)
                    Objects.requireNonNull(error.getArguments())[0];

            errorMessage.append("传参错误").append(index++).append(":");
            errorMessage.append("参数")
                    .append(argument.getDefaultMessage())
                    .append(error.getDefaultMessage())
                    .append(";  ");
        }
        todoErrorLogger(e, e.getMessage());
        return Result.fail(errorMessage.toString(),false);
    }

    /**
     * spring validator 方法参数验证异常拦截
     *
     * @param e 绑定验证异常
     * @return 错误返回消息
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<Boolean> defaultErrorHandler(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        todoErrorLogger(e,e.getMessage());
        return Result.fail(violation.getMessage(),false);
    }

    @ExceptionHandler(BusinessException.class) //指定什么异常执行这个方法
    @ResponseBody //为了返回给前端数据
    public Result<Boolean> doBusinessException(BusinessException e)
    {
        todoErrorLogger(e,e.getMessage());
        return Result.fail(e.getMessage(),false);
    }


    @ExceptionHandler(Exception.class) //指定什么异常执行这个方法
    @ResponseBody //为了返回给前端数据
    public Result<Boolean> doException(Exception e)
    {
        todoErrorLogger(e,e.getMessage());
        return Result.fail(e.getMessage(),false);
    }

    private void todoErrorLogger(Exception e, String customErrorMsg)
    {
        StringBuilder sb = new StringBuilder();
        sb.append(e.getClass().getName()).append(":");
        if (customErrorMsg != null)
        {
            sb.append(customErrorMsg);
        } else {
            sb.append(e.getMessage());
        }
        StackTraceElement[] elements = e.getStackTrace();
        if(elements.length > 0)
        {
            StackTraceElement element = elements[0];
            sb.append("##function:").append(element.getClassName()).append("-").append(element.getMethodName()).append("-").append(element.getLineNumber());
        }
        LOGGER.info("error:{}",sb.toString());
        e.printStackTrace();
    }
}
